using System;
using System.Collections.Generic;
using TerritoryGame.Domain.Entities;

namespace TerritoryGame.Domain.Entities.App
{
    public class UserLevel : EntityBase
    {
        public Guid UserId { get; set; } // 用户ID
        public int CurrentLevel { get; set; } = 1; // 当前等级
        public int CurrentExperience { get; set; } = 0; // 当前经验值
        public int TotalExperience { get; set; } = 0; // 总经验值
        public string CurrentTitle { get; set; } = "墨痕初绽"; // 当前称号
        public List<string> UnlockedTitles { get; set; } = new List<string>(); // 已解锁的称号列表
        public DateTime LastLevelUpTime { get; set; } = DateTime.UtcNow; // 最后升级时间
        
        // Navigation property
        public User User { get; set; } = null!;
        
        // 计算升级所需经验值
        public int GetExperienceRequiredForNextLevel()
        {
            // 如果已经达到最高等级20级，则不需要经验值
            if (CurrentLevel >= 20)
                return 0;
                
            return CalculateExperienceForLevel(CurrentLevel + 1);
        }
        
        // 计算指定等级所需的总经验值
        public static int CalculateExperienceForLevel(int level)
        {
            // 优化后的经验值公式：2-3把游戏升1级
            // 1级需要150经验，2级需要300经验，3级需要450经验...
            // 每级递增150经验值，让升级更容易
            return level * 150;
        }
        
        // 添加经验值并检查是否升级
        public bool AddExperience(int experience)
        {
            CurrentExperience += experience;
            TotalExperience += experience;
            
            bool leveledUp = false;
            
            // 只有当前等级小于20级时才能升级
            while (CurrentLevel < 20 && CurrentExperience >= GetExperienceRequiredForNextLevel())
            {
                CurrentExperience -= GetExperienceRequiredForNextLevel();
                CurrentLevel++;
                LastLevelUpTime = DateTime.UtcNow;
                leveledUp = true;
                
                // 检查是否解锁新称号
                CheckAndUnlockTitles();
            }
            
            return leveledUp;
        }
        
        // 检查并解锁称号
        private void CheckAndUnlockTitles()
        {
            var newTitle = GetTitleForLevel(CurrentLevel);
            if (!string.IsNullOrEmpty(newTitle) && !UnlockedTitles.Contains(newTitle))
            {
                UnlockedTitles.Add(newTitle);
                CurrentTitle = newTitle; // 自动设置为最新称号
            }
        }
        
        // 根据等级获取称号
        public static string GetTitleForLevel(int level)
        {
            return level switch
            {
                1 => "墨痕初绽",
                5 => "玄疆漫步",
                10 => "万象染境",
                15 => "永夜封疆",
                20 => "无界墨尊",
                _ => level >= 20 ? "无界墨尊" : null
            };
        }
        
        // 获取所有可用称号
        public static List<string> GetAllTitles()
        {
            return new List<string>
            {
                "墨痕初绽", "玄疆漫步", "万象染境", "永夜封疆", "无界墨尊"
            };
        }
    }
}
